<?php

namespace App\Http\Controllers\Admin\Customer;

use App\Http\Controllers\Admin\Base\ExchangeRate;
use App\Http\Controllers\Controller;
use App\Models\base\CurrencyModel;
use App\Models\cainiao\AsnModel;
use App\Models\customer\RepairModel;
use App\Models\finance\ReceivableGenericModel;
use App\Models\lazada\BigBagModel;
use App\Models\OrderModel;
use App\Models\RecBillIdsModel;
use App\Models\RecBillModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class Receivable extends Controller
{
    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $order_code = $request->input('order_code', '');
        $bigBagID = $request->input('bigBagID', '');
        $take_order_sn = $request->input('take_order_sn', '');
        $customer_id = $request->input('customer_id', '');
        $create_start = $request->input('startTime', '');
        $create_end = $request->input('endTime', '');
        $des_country_id = $request->input('des_country_id', '');
        $node_id = $request->input('node_id', '');

        $query = ReceivableGenericModel::with(['flight', 'customer', 'notify', 'take_order'])->whereHas('customer', function($query) {
            $query->where('is_big', 1);
        });

        if($take_order_sn){
            $query->whereHas('take_order', function($query) use ($take_order_sn) {
                $query->where('sn', 'like', $take_order_sn);
            });
        }

//        if ($order_code) {
//            $query->where('logisticsOrderCode', $order_code);
//        }
//
        if($bigBagID){
            $take_order_id = BigBagModel::where('bigBagID', $bigBagID)->value('take_order_id');
            $query->where('take_order_id', $take_order_id);
        }
//
//        if ($des_country_id) {
//            $query->where('des_country_id', $des_country_id);
//        }

        if($customer_id){
            $query = $query->where('customer_id', $customer_id);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'customer_name' => $item->customer->name ?? '',
                'take_order_sn' => $item->take_order->sn ?? '',
                'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->goods_attr] ?? '',
                'take_off_time' => $item->flight->take_off_time ?? '',
                'landing_time' => $item->flight->landing_time ?? '',
                'start_port_code' => $item->flight->start_port_code ?? '',
                'arrive_port_code' => $item->flight->arrive_port_code ?? '',
                'big_pkgs' => $item->package_num,
                'small_pkgs' => $item->notify?->sum('parcelQty') ?? 0,
                'reality_weight' => $item->charging_weight,
                'price' => $item->big_line_price,
                'total_amount' => $item->total_amount,
                'weight' => $item->charging_weight,
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }


    public function update(Request $request, $id) {
        $weight = $request->input('weight', 0);
        $price = $request->input('price', 0);

        $model = ReceivableGenericModel::find($id);
        if(!$model){
            return $this->error('找不到该提单');
        }

        $model->charging_weight = $weight;
        $model->big_line_price = $price;
        $model->total_amount = round($weight * $price, 2);
        $model->save();

        return $this->success();
    }


    public function repair(Request $request)
    {
        $auth = $request->get('auth');
        $params = $request->all();
        $validator = Validator::make($params, [
            'ids' => 'required',
            'subject_id' => 'required',
            'currency_id' => 'required|integer',
            'amount' => 'required'
        ], [
            'ids.required' => '请选择补录小包',
            'subject_id.required' => '请选择科目',
            'currency_id.required' => '请选择币种',
            'amount.required' => '请填写金额',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        foreach ($params['ids'] as $id){
            $repair = new RepairModel();
            $repair->subject_id = $params['subject_id'];
            $repair->currency_id = $params['currency_id'];
            $repair->amount = $params['amount'];
            $repair->remarks = $params['remarks'] ?? '';
            $repair->asn_id = $id;
            $repair->created_admin_id = $auth->id;
            $repair->save();
        }
        return $this->success();
    }

    public function bill_create(Request $request)
    {
        $ids = $request->input('ids', []);
        $currency_id = $request->input('currency_id', 0);
        if(empty($ids)){
            return $this->error('请选择要生成账单的提单');
        }
        if(!$currency_id){
            return $this->error('请选择币种');
        }

        $items = ReceivableGenericModel::with(['notify', 'customer'])
            ->whereIn('id', $ids)
            ->whereNull('bill_id')
            ->get();

        if(count($items) != count($ids)){
            return $this->error('请选择未出账的提单');
        }

        $list = $items->map(function($item){
            $res = [
                'id' => $item->id,
                'customer_id' => $item->customer_id,
                'customer_name' => $item->customer->name ?? '',
                'small_count' => $item->notify?->sum('parcelQty') ?? 0,
                'big_count' => $item->notify?->count() ?? 0,
                'total_amount' => $item->total_amount,
            ];
            return $res;
        });

        $statistics = [];
        foreach ($list as $item){
            if(isset($statistics[$item['customer_id']])){
                $statistics[$item['customer_id']]['small_count'] += $item['small_count'];
                $statistics[$item['customer_id']]['big_count'] += $item['big_count'];
                $statistics[$item['customer_id']]['take_order_count'] += 1;
                $statistics[$item['customer_id']]['total_amount'] += $item['total_amount'];
            }else{
                $statistics[$item['customer_id']] = [
                    'customer_id' => $item['customer_id'],
                    'customer_name' => $item['customer_name'],
                    'small_count' => $item['small_count'],
                    'big_count' => $item['big_count'],
                    'take_order_count' => 1,
                    'total_amount' => $item['total_amount'],
                ];
            }
        }

        $return = [];
        foreach ($statistics as $val){
            $return[] = [
                'customer_id' => $val['customer_id'],
                'customer_name' => $val['customer_name'],
                'small_count' => $val['small_count'],
                'big_count' => $val['big_count'],
                'take_order_count' => $val['take_order_count'],
                'total_amount' => $val['total_amount'],
            ];
        }

        return $this->success(['list' => $return]);

    }

    public function confirm_bill(Request $request)
    {
        $ids = $request->input('ids', []);
        $currency_id = $request->input('currency_id', 0);
        $start = $request->input('start', '');
        $end = $request->input('end', '');
        $remark = $request->input('remark', '');
        if(empty($ids)){
            return $this->error('请选择要生成账单的小包');
        }
        if(!$currency_id){
            return $this->error('请选择币种');
        }

        $items = ReceivableGenericModel::with(['notify', 'customer'])->whereIn('id', $ids)->get();

        $list = $items->map(function($item){
            $res = [
                'id' => $item->id,
                'take_order_id' => $item->take_order_id,
                'customer_id' => $item->customer_id,
                'customer_name' => $item->customer->name ?? '',
                'small_count' => $item->notify?->sum('parcelQty') ?? 0,
                'big_count' => $item->notify?->count() ?? 0,
                'total_amount' => $item->noyfy?->sum('total_amount') ?? 0,
            ];
            return $res;
        });

        $statistics = [];
        foreach ($list as $item){
            if(isset($statistics[$item['customer_id']])){
                $statistics[$item['customer_id']]['small_count'] += $item['small_count'];
                $statistics[$item['customer_id']]['big_count'] += $item['big_count'];
                $statistics[$item['customer_id']]['take_order_count'] += 1;
                $statistics[$item['customer_id']]['take_order_id'][] = $item['take_order_id'];
                $statistics[$item['customer_id']]['total_amount'] += $item['total_amount'];
            }else{
                $statistics[$item['customer_id']] = [
                    'customer_id' => $item['customer_id'],
                    'customer_name' => $item['customer_name'],
                    'small_count' => $item['small_count'],
                    'big_count' => $item['big_count'],
                    'take_order_count' => 1,
                    'take_order_id' => [$item['take_order_id']],
                    'total_amount' => $item['total_amount'],
                ];
            }
        }

        $customer_bill = $statistics;

        $currency = CurrencyModel::find($currency_id)->short_code;

        $auth = $request->get('auth');
        DB::beginTransaction();
        try {
            foreach($customer_bill as $bill) {
                $rec_bill = new RecBillModel();
                $rec_bill->sn = getCode('rec_bill', 'ZD', 5);
                $rec_bill->customer_id = $bill['customer_id'];
                $rec_bill->currency = $currency;
                $rec_bill->amount = $bill['total_amount'];
                $rec_bill->remark = $remark;
                $rec_bill->start = $start;
                $rec_bill->end = $end;
                $rec_bill->take_order_count = $bill['take_order_count'];
                $rec_bill->big_count = $bill['big_count'];
                $rec_bill->small_count = $bill['small_count'];
                $rec_bill->created_admin_id = $auth->id;
                $rec_bill->save();

                ReceivableGenericModel::whereIn('id', $ids)->update([
                    'bill_id' => $rec_bill->id
                ]);

                BigBagModel::whereIn('take_order_id', $bill['take_order_id'])->update([
                    'rec_bill_id' => $rec_bill->id
                ]);
            }

            //提单出账状态改为已出账
            TakeOrderModel::whereIn('id', $ids)->update([
                'rec_bill_status' => 2
            ]);

            DB::commit();

        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }


        return $this->success();
    }



}
